package com.tbeasy.financial;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tbeasy.financial.data.TransactionItem;
import com.tbeasy.financial.provider.DatabaseUtil.TableTransaction;
import com.tbeasy.financial.util.Util;

public class AccountActivity extends Activity {

//	private static final int DIALOG_DATE = 1;

	private TextView monthTextView;
	private TextView todayView;
	private TextView weekView;
	private TextView monthView;
	private TextView weekIncomeView;
	private TextView weekCostView;
	private TextView monthIncomeView;
	private TextView monthCostView;
	private TextView accountIncomeView;
	private TextView accountCostView;
	private TextView todayCostView;
	private TextView todayIncomeView;

	private Button typeButton;
	private Button submitButton;
	private EditText contentText;

	private Double todayIncome = 0.0;
	private Double todayCost = 0.0;
	private Double weekIncome = 0.0;
	private Double weekCost = 0.0;
	private Double monthIncome = 0.0;
	private Double monthCost = 0.0;

	private ArrayList<TransactionItem> allItems = new ArrayList<TransactionItem>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account);
		initView();

		checkValue();
	}

	private void checkValue() {
		getAllItems();
		
		for (TransactionItem item : allItems) {
			updateIncomeAndCostValue(item);
		}

		updateDisplay();
	}
	
	private void updateDisplay() {
		weekCostView.setText("-￥" + weekCost);
		weekIncomeView.setText("+￥" + weekIncome);
		monthCostView.setText("-￥" + monthCost);
		monthIncomeView.setText("+￥" + monthIncome);
		accountCostView.setText("￥" + monthCost + "");
		accountIncomeView.setText("￥" + monthIncome + "");
		todayCostView.setText("-￥" + todayCost);
		todayIncomeView.setText("+￥" + todayIncome);
	}
	
	private void updateIncomeAndCostValue(TransactionItem item) {
		long weekFirst = Util.getMonday(new Date()).getTime();
		long weeklast = Util.getSaturday(new Date()).getTime();
		long todayFirst = Util.getTodayFirstTime();
		long todayLast = Util.getTodayLastTime();
		long addTime = item.getAddTime();
		if (weekFirst < addTime && addTime < weeklast) {
			if (item.getCategoryId() == 1) {
				weekCost += Double.valueOf(item.getAmount());
			} else {
				weekIncome += Double.valueOf(item.getAmount());
			}
		}
		if (addTime > Util.getCurrentMonthTime()) {
			if (item.getCategoryId() == 1) {
				monthCost += Double.valueOf(item.getAmount());
			} else {
				monthIncome += Double.valueOf(item.getAmount());
			}
		}

		if (addTime >= todayFirst && addTime <= todayLast) {
			if (item.getCategoryId() == 1) {
				todayCost += Double.valueOf(item.getAmount());
			} else {
				todayIncome += Double.valueOf(item.getAmount());
			}
		}
	}

	private void getAllItems() {
		Cursor cursor = getContentResolver().query(
				TableTransaction.CONTENT_URI,
				new String[] { TableTransaction.TRANSACTION_ID, TableTransaction.BUYER_MONEY,
						TableTransaction.CREATE_TIME, TableTransaction.CATEGORY_ID, TableTransaction.MEMO }, null,
				null, TableTransaction.CREATE_TIME + " desc");
		TransactionItem item = null;
		while (cursor.moveToNext()) {
			item = new TransactionItem();
			item.setId(cursor.getInt(0));
			item.setAmount(cursor.getString(1));
			item.setAddTime(cursor.getLong(2));
			item.setCategoryId(cursor.getInt(3));
			item.setMemo(cursor.getString(4));
			allItems.add(item);
		}
	}

	private void initView() {
		monthTextView = (TextView) findViewById(R.id.account_month);
		monthView = (TextView) findViewById(R.id.account_month_detail);
		weekView = (TextView) findViewById(R.id.account_week_detail);
		todayView = (TextView) findViewById(R.id.account_today_detail);

		weekCostView = (TextView) findViewById(R.id.week_cost);
		weekIncomeView = (TextView) findViewById(R.id.week_income);
		monthCostView = (TextView) findViewById(R.id.month_cost);
		monthIncomeView = (TextView) findViewById(R.id.month_income);
		accountCostView = (TextView) findViewById(R.id.account_expand);
		accountIncomeView = (TextView) findViewById(R.id.account_income);
		todayCostView = (TextView) findViewById(R.id.today_cost);
		todayIncomeView = (TextView) findViewById(R.id.today_income);

		typeButton = (Button) findViewById(R.id.type);
		typeButton.setTag(1);
		submitButton = (Button) findViewById(R.id.submit_btn);
		contentText = (EditText) findViewById(R.id.content);

		submitButton.setOnClickListener(viewClickListener);
		typeButton.setOnClickListener(viewClickListener);

		Calendar calendar = Calendar.getInstance();
		monthTextView.setText((calendar.get(Calendar.MONTH) + 1) + "月");
		monthView.setText(Util.getMonthValue());
		todayView.setText(getTodayValue());
		weekView.setText(Util.getWeekValue());
	}

	private OnClickListener viewClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.submit_btn:
				addTransaction();
				break;

			case R.id.type:
				if (((Integer) typeButton.getTag()) == 1) {
					typeButton.setText("收入");
					typeButton.setTag(0);
				} else {
					typeButton.setText("支出");
					typeButton.setTag(1);
				}
				break;
			}
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
//		case DIALOG_DATE:
//			final Calendar c = Calendar.getInstance();
//			return new DatePickerDialog(this, mDateSetListener, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
//					c.get(Calendar.DAY_OF_MONTH));
		}
		return null;
	}

//	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
//
//		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//			mYear = year;
//			mMonth = monthOfYear + 1;
//			mDay = dayOfMonth;
//		}
//	};

	private String getTodayValue() {
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
		return dateFormat.format(date);
	}

	protected void addTransaction() {

		long time = System.currentTimeMillis();
		int type = (Integer) typeButton.getTag();
		Double money = 0.0;
		String memo = "";
		String content = contentText.getText().toString().trim();
		memo = content.substring(content.indexOf(" "), content.length()-1);
		try {
			money = Double.valueOf(content.substring(0, content.indexOf(" ")).trim());
		} catch (Exception e) {
			Toast.makeText(this, "亲，金额好像不对吧,一定要放在前面并且用空格分开哦", Toast.LENGTH_SHORT).show();
			return;
		}
		ContentValues values = new ContentValues();
		values.put(TableTransaction.CATEGORY_ID, type);
		values.put(TableTransaction.CREATE_TIME, time);
		values.put(TableTransaction.MEMO, memo);
		values.put(TableTransaction.BUYER_MONEY, money);
		Uri uri = getContentResolver().insert(TableTransaction.CONTENT_URI, values);
		if(uri != null) {
			Toast.makeText(this, "添加账目成功", Toast.LENGTH_SHORT).show();
			contentText.setText("");
			TransactionItem item = new TransactionItem();
			item.setAddTime(time);
			item.setAmount(money+"");
			item.setCategoryId(type);
			item.setMemo(memo);
			updateIncomeAndCostValue(item);
			updateDisplay();
		} else {
			Toast.makeText(this, "哦，失败了，再试一次吧！", Toast.LENGTH_SHORT).show();
		}
	}

}
